package com.tyc.waitnotify;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition一定要在锁内使用
 * 每个Condition关联了一个等待队列
 * 当调用 await方法 同步队列的头节点放入等待队列的尾节点
 * 调用signal方法将等待队列的头节点防止同步队列的尾节点
 *
 * @author tyc
 * @version 1.0
 * @date 2021-09-03 10:14:32
 */
public class ConditionTest {
    private static final Lock lock = new ReentrantLock();
    private static String target = "A";

    public static void main(String[] args) {
        Condition a = lock.newCondition();
        Condition b = lock.newCondition();
        Condition c = lock.newCondition();

        new Thread(()->{
            lock.lock();
            try {
                if(!target.equals("A")){
                    a.await();
                }
                System.out.println("A");
                target = "B";
                b.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
        new Thread(()->{
            lock.lock();
            try {
                if(!target.equals("B")){
                    b.await();
                }
                System.out.println("B");
                target = "C";
                c.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
        new Thread(()->{
            lock.lock();
            try {
                if(!target.equals("C")){
                    c.await();
                }
                System.out.println("C");
                target = "A";
                a.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
    }

}
